const fs = require("fs")
const fse = require("fs-extra")
const sysPath = require("path")
const templates = fs.readdirSync(sysPath.resolve(__dirname, "../../packages"))
                    .filter(template => template.indexOf("plugin") > -1)
//移出老版本的目录
let vueTemplates = templates.filter((template) => (template.indexOf("vue") > -1 && template.indexOf("old") == -1))
let reactTemplates = templates.filter((template) => (template.indexOf("vue") == -1 && template.indexOf("svelte") == -1 && template.indexOf("old") == -1))

deletePath("react deleteFiles", "react")
deletePath("vue deleteFiles", "vue")
deletePath("deleteFiles")

async function deletePath(src, type) {
  // 读取目录中的所有文件/目录
  let paths = fs.readdirSync(sysPath.join(__dirname, src))

  if (paths.length == 0) {
    let tempPath = src.split(sysPath.sep)
    tempPath.shift()
    tempPath = tempPath.join(sysPath.sep)
    if (tempPath === "") {
      return
    }
    let packages = type === undefined ? templates : type === "vue" ? vueTemplates : reactTemplates
    packages.forEach((packageName) => {
      let targetPath = sysPath.resolve(__dirname, `../../packages/${packageName}/${tempPath}`)
      fse.removeSync(sysPath.resolve(__dirname, targetPath))
    })
    if (type == undefined) {
      ["react", "vue"].forEach((type) => {
        fse.removeSync(sysPath.resolve(__dirname, `../../templates/${type}/${tempPath}`))
      })
    }else {
      fse.removeSync(sysPath.resolve(__dirname, `../../templates/${type}/${tempPath}`))
    }

  }
  for (let i = 0; i < paths.length; i++) {
    let _src = src + sysPath.sep + paths[i]
    // 判断是否为文件
    let fileStat = await stat(sysPath.join(__dirname, _src))
    if (fileStat.isFile()) {
      let tempPath = _src.split(sysPath.sep)
      tempPath.shift()
      tempPath = tempPath.join(sysPath.sep)
      let packages = type === undefined ? templates : type === "vue" ? vueTemplates : reactTemplates
      packages.forEach((packageName) => {
        let basePath = `../../packages/${packageName}`
        deleteFun(tempPath, basePath)
      })
      if (type == undefined) {
        ["react", "vue"].forEach((type) => {
          deleteFun(tempPath, `../../templates/${type}`)
        })
        return
      }
      deleteFun(tempPath, `../../templates/${type}`)
    }
    // 如果是目录则递归调用自身
    else if (fileStat.isDirectory()) {
      await deletePath(_src, type)
    }
  }

}

function deleteFun(tempPath, basePath) {
  let targetPath = sysPath.resolve(__dirname, `${basePath}/${tempPath}`)
  let targetDir = targetPath.split(sysPath.sep)
  targetDir.pop()
  targetDir = targetDir.join(sysPath.sep)
  let dirIsExist = fs.existsSync(targetDir)
  if (!dirIsExist) {
    return
  }
  fse.removeSync(sysPath.resolve(__dirname, targetPath))

}

//封装stat为promise
async function stat(path) {
  return new Promise((resolve, reject) => {
    fs.stat(path, function(err, data) {
      if (err) {
        reject(err)
      }
      resolve(data)
    })
  })
}